<template>
  <el-button type="primary">测试按钮</el-button>
  <div style="height: 300px">
    <component :is="remote" v-if="remote" v-model="name" @childClick="childClick" />
  </div>
  <div style="height: 300px">
    <component :is="remote1" v-if="remote1" />
  </div>
</template>

<script setup lang="ts">
import { loadModule } from 'vue3-sfc-loader'
import * as Vue from 'vue'
import { onMounted, defineAsyncComponent, ref, watchEffect, type Ref } from 'vue'
import CusLayout from './components/CusLayout.vue'
import { useData } from '@/views/components/useData'

const remote = ref<unknown>()
const name = ref('李四')
const url = 'http://localhost:3000/getVue3Str'
const remote1 = ref<unknown>()
const url1 = 'http://localhost:3000/getVue3Table'

onMounted(() => {
  load(remote, url)
  load(remote1, url1)
})

watchEffect(() => {
  console.log(name.value)
})

const childClick = (newVal: string) => {
  console.log('子组件点击事件', newVal)
}

// ### 怎么加载远程表格的组件？
const BaseAgGrid = defineAsyncComponent(() => import('@/components/BaseAgGrid.vue'))
// 加载远程文件
const load = async (cmpRef: Ref<unknown>, url: string) => {
  const res = await fetch(url).then((res) => res.json())

  const options = {
    moduleCache: {
      vue: Vue,
      BaseAgGrid: BaseAgGrid,
      CusLayout: CusLayout,
      useData: useData
    },
    async getFile() {
      return res.fileStr
    },
    addStyle(textContent: string) {
      const style = Object.assign(document.createElement('style'), {
        textContent,
      })
      const ref = document.head.getElementsByTagName('style')[0] || null
      document.head.insertBefore(style, ref)
    },
  }

  // 加载远程组件
  cmpRef.value = Vue.markRaw(
    defineAsyncComponent(() => loadModule(res.fileName || 'loader.vue', options)),
  )
}
</script>

<style scoped></style>
